package com.example.qrcodecamera;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class MaterialDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "MaterialDB.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "materials";

    public MaterialDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "material_id TEXT," +
                "material_name TEXT," +
                "specification TEXT," +
                "current_weight REAL)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    // 插入数据
    public boolean insertData(String id, String name, String spec, double weight) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("material_id", id);
        values.put("material_name", name);
        values.put("specification", spec);
        values.put("current_weight", weight);
        return db.insert(TABLE_NAME, null, values) != -1;
    }

    // 分页查询
    public List<MaterialInfo> getPagedData(int page, int pageSize) {
        List<MaterialInfo> data = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "SELECT * FROM " + TABLE_NAME +
                        " LIMIT " + pageSize +
                        " OFFSET " + (page-1)*pageSize, null);

        if (cursor.moveToFirst()) {
            do {
                data.add(new MaterialInfo(
                        cursor.getString(1),  // material_id
                        cursor.getString(2),  // material_name
                        cursor.getString(3),  // specification
                        cursor.getDouble(4)   // current_weight
                ));
            } while (cursor.moveToNext());
        }
        cursor.close();
        return data;
    }

    // 获取总记录数
    public int getTotalCount() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_NAME, null);
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        cursor.close();
        return count;
    }
}